﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Elmah;
using Viettel.VOFFICE.DAO.Models;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;

namespace Viettel.VOFFICE.Web.Controllers
{
    public class PositionController : BaseController
    {
        //
        // GET: /Position/
        [HttpGet]
        [ActionName("get_list")]
        public JsonResult GetList(int pageIndex = 0, int pageSize = 0)
        {
            //có phân trang
            try
            {
                if (pageSize > 0 && pageIndex >= 0)
                {
                    var list = unitOfWork.PositionRepository.Pading(pageIndex, pageSize);
                    return Json(new JsonResponse()
                    {

                        Status = true,
                        Result = new
                        {
                            PageIndex = list.PageIndex,
                            PageSize = list.PageSize,
                            PageCount = list.PageCount,
                            List = list.Select(o => new PositionModel(o))
                        }
                    }, JsonRequestBehavior.AllowGet);
                }
                //không phân trang
                else
                {

                    var list = unitOfWork.PositionRepository.Get().Select(o => new PositionModel(o));
                    return Json(new JsonResponse() { Status = true, Result = list }, JsonRequestBehavior.AllowGet);
                } //end if
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(new NotSupportedException("", ex));
                return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                throw;
            }//end try
        }

        [HttpPut]
        [ActionName("update_item")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult UpdateItem(PositionModel model, string modified = "all")
        {
            try
            {
                List<ValidationResult> outError;
                if (model.IsValid(out outError))
                {
                    var dbPosition = unitOfWork.PositionRepository.GetById(model.Id);
                    if (dbPosition == null)
                    {
                        return Json(new JsonResponse()
                        {
                            Status = false,
                            Result = "Không cập nhật được đâu"
                        });
                    }
                    if (modified.ToUpper().Contains("ISACTIVE"))
                    {
                        dbPosition.IsActive = model.IsActive;
                    }
                    else//cập nhập hết
                    {
                        dbPosition.Name = model.Name;
                        dbPosition.Description = model.Description;
                        dbPosition.IsActive = model.IsActive;
                    }//end if
                    dbPosition.UpdatedAt = DateTime.Now;
                    unitOfWork.PositionRepository.Update(dbPosition);
                    return Json(SimplyResponse.Response200());
                }
                else
                {
                    return Json(new JsonResponse()
                    {
                        Status = false,
                        Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                    });
                }//end ìf
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }


        [HttpPost]
        [ActionName("add_item")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult AddItem(PositionModel model)
        {
            try
            {
                try
                {
                    List<ValidationResult> outError;
                    if (model.IsValid(out outError))
                    {
                        var dbPosition = new v_Position
                        {
                            Name = model.Name,
                            Description = model.Description,
                            IsActive = model.IsActive,
                            CreatedAt = DateTime.Now,
                            UpdatedAt = DateTime.Now
                        };
                        unitOfWork.PositionRepository.Insert(dbPosition);
                        return Json(SimplyResponse.ResposeWithId(dbPosition.Id));
                    }
                    else
                    {
                        return Json(new JsonResponse()
                        {
                            Status = false,
                            Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                        });
                    }//end ìf
                }
                catch (Exception)
                {
                    return Json(SimplyResponse.Response500());
                    //throw;
                }
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }


        [HttpPost]
        [ActionName("delete_item")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult DeleteItem(int id)
        {
            var pos = unitOfWork.PositionRepository.GetById(id);
            if (pos != null)
            {
                unitOfWork.PositionRepository.Delete(id);
                return Json(SimplyResponse.Response200());
            }
            return Json(SimplyResponse.Response500());
        }


    }
}
